package com.xiaocikuai.smallchunks.service.Product;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaocikuai.smallchunks.entity.Advertise.ImgUni;
import com.xiaocikuai.smallchunks.entity.Card.CardChunks;
import com.xiaocikuai.smallchunks.entity.Product.ProInfo;
import com.xiaocikuai.smallchunks.entity.Product.ProInfoList;
import com.xiaocikuai.smallchunks.entity.Product.Product;
import com.xiaocikuai.smallchunks.entity.Product.Plan;
import com.xiaocikuai.smallchunks.entity.Transaction.MaleList;
import com.xiaocikuai.smallchunks.entity.Transaction.YshopMaleList;
import com.xiaocikuai.smallchunks.entity.Transaction.YshopRedemptionCode;
import com.xiaocikuai.smallchunks.entity.User.User;
import com.xiaocikuai.smallchunks.file.PutObject004;
import com.xiaocikuai.smallchunks.mapper.Card.CardChunksMapper;
import com.xiaocikuai.smallchunks.mapper.Product.ProductMapper;
import com.xiaocikuai.smallchunks.mapper.Recode.RecodeMapper;
import com.xiaocikuai.smallchunks.mapper.Transaction.MaleListMapper;
import com.xiaocikuai.smallchunks.mapper.Transaction.TransactionMapper;
import com.xiaocikuai.smallchunks.service.Recode.RecodeService;
import com.xiaocikuai.smallchunks.utils.JWTservice.JwtService;
import com.xiaocikuai.smallchunks.utils.ListStringUtil.ListStringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class ProductService extends ServiceImpl<ProductMapper, Product> {

    @Resource
    private ProductMapper productMapper;

    @Resource
    private CardChunksMapper cardChunksMapper;

    @Resource
    private JwtService jwtService;

    @Resource
    private RecodeMapper recodeMapper;

    @Resource
    private TransactionMapper transactionMapper;

    @Autowired
    private PutObject004 putObject004;

    @Resource
    private MaleListMapper maleListMapper;

    @Resource
    private RecodeService recodeService;


    // 获取产品列表
    public List<Product> getProductList(String token, Product product) {
            int uid = jwtService.deconstruction(token).getUid();
            List<Product> productList = productMapper.productlist(product.getClas(), product.getClasses());
            List<Integer> pidList = productMapper.getUnlockPid(uid);
            for (Product pro:productList){
                if (pidList.contains(pro.getPid()))
                    pro.setLocked(1);
            }
            productList.sort(Comparator.comparingInt(Product::getLocked).reversed());
            return productList;
    }

//    // 未登录获取产品列表
//    public List<Product> getProductList(String token, Product product) {
//        int uid = jwtService.deconstruction(token).getUid();
//        List<Product> productList = productMapper.productlist(product.getClas(), product.getClasses());
//        List<Integer> pidList = productMapper.getUnlockPid(uid);
//        for (int pid:pidList){
//            productList.get(pid).setLocked(1);
//        }
//        return productList;
//    }



    // 获取产品详情
    public List<ProInfoList> getDayProduct(Plan plan, String token) {
        int uid = jwtService.deconstruction(token).getUid();

        List<Integer> pidList = productMapper.getUnlockPid(uid);
        if (!pidList.contains((plan.getPrductId()))){
            return null;
        }

        int cardTotal = productMapper.countByProductId(plan.getPrductId());
        int dayCards = plan.getPlan();
        int periodLength = 10;

        // 预先计算周期数
        int periodsCount = (int) Math.ceil((double) cardTotal / (dayCards * periodLength));

        List<ProInfoList> proInfoLists = new ArrayList<>();
        int index = 0;
        int startCardIndex = 0;

        for (int i = 0; i < periodsCount; i++) {
            int startDay = startCardIndex / dayCards + 1;
            int endDay = Math.min(startDay + periodLength - 1, cardTotal / dayCards);

            if ((i == periodsCount - 1) && (startCardIndex < cardTotal)) {
                startDay = startCardIndex / dayCards + 1;
                endDay = startDay + (cardTotal - startCardIndex + dayCards - 1) / dayCards - 1;
            }

            // 一次性获取当前周期内的所有 ProInfo 对象
            List<ProInfo> proInfos = new ArrayList<>();
            for (int j = startDay; j <= endDay; j++) {
                proInfos.add(new ProInfo(j, String.format("Day %d", j), returnTag(plan, uid, j, cardTotal)));
            }

            proInfoLists.add(new ProInfoList(index++, String.format("%s-%s Day", startDay, endDay), proInfos));
            startCardIndex += periodLength * dayCards;
        }
        return proInfoLists;
    }

    public int returnTag(Plan plan, int uid, int j, int total){
        int pid = plan.getPrductId();
        int begin = plan.getPlan() * (j-1);
        int end = Math.min((plan.getPlan() * j) - 1, total-1);
        Integer cidBegin = productMapper.getCidsss(begin,pid);
        Integer cidEnd = productMapper.getCidsss(end,pid);
        if (productMapper.getE(uid, pid,cidBegin) != null){
            if (productMapper.getE(uid,pid, cidEnd) != null){
                return 2;
            } else {
                return 1;
            }
        }
        return 0;
    }


    // 获取该日需学习的单词
    public List<CardChunks> getPlans(String token, Plan plans) {
        try {
            // 解析token获取用户信息
            User user = jwtService.deconstruction(token);

            int today = (plans.getDay() - 1) * plans.getPlan();
            int cardTotal = productMapper.countByProductId(plans.getPrductId());
            List<CardChunks> todayCards = new ArrayList<>();
            List<CardChunks> allCards = productMapper.allByProductId(plans.getPrductId());

            for (int i = 0; (i < plans.getPlan()) && (today < cardTotal); i++) {
                allCards.get(today).setIsCollect(cardChunksMapper.isCollect(allCards.get(today).getCid(), user.getUid()));
                if (recodeMapper.isCorrect(allCards.get(today).getCid(), user.getUid()) == null) {
                    allCards.get(today).setIsCorrect(0);
                } else {
                    allCards.get(today).setIsCorrect(recodeMapper.isCorrect(allCards.get(today).getCid(), user.getUid()));
                }
                todayCards.add(allCards.get(today));
                today++;
            }
            return todayCards;
        } catch (Exception e) {
            return null; // 或者返回空列表，具体视情况而定
        }
    }


    public boolean deleteToday(String token, Plan plans) {
        int uid = jwtService.deconstruction(token).getUid();
        int today = (plans.getDay() - 1) * plans.getPlan();
        int cardTotal = productMapper.countByProductId(plans.getPrductId());
        List<CardChunks> allCards = productMapper.allByProductId(plans.getPrductId());
        for (int i = 0; (i < plans.getPlan()) && (today < cardTotal); i++) {

            productMapper.deleteToday(allCards.get(today).getCid(), uid);
            today++;
        }
        return true;
    }




    //获取产品全部信息
    public Product getInfo(int pid,String token) {
        int uid = jwtService.deconstruction(token).getUid();
        List<Integer> pidList = productMapper.getUnlockPid(uid);
        if (pidList.contains(pid))
            return productMapper.getInfo(pid);
        else
            return null;
    }

    //录入单词
    public String enterWord(int pid, List<Integer> cidS) {
        try {
            for (int cid : cidS) {
                productMapper.enterWord(pid, cid);
            }
            return "录入成功";
        } catch (Exception e) {
            return "录入失败，原因：${e.getMessage()}";
        }
    }

    //获取商品信息
    public List<YshopMaleList> getShopInfoList(int pid) {
        String tidS = productMapper.getShopTidS(pid);
        List<Integer> tidList =  Arrays.stream(tidS.substring(1, tidS.length() - 1).split(","))
                .map(Integer::parseInt)
                .toList();
        List<YshopMaleList> yshopMaleLists = new ArrayList<>();
        for (int tid: tidList){
            yshopMaleLists.add(productMapper.getShopinfo(tid));
        }
        return yshopMaleLists;
    }

    public List<HashMap<String, Object>> getShopHashMap(int tid) {
        String arrayString = productMapper.getIntroduce(tid);
        // 定义正则表达式模式，用于匹配数组中的元素
        Pattern pattern = Pattern.compile("\\[(.*?)\\]");
        Matcher matcher = pattern.matcher(arrayString);

        List<HashMap<String, Object>> resultList = new ArrayList<>();

        while (matcher.find()) {
            String pair = matcher.group(1);
            String[] keyValue = pair.split(",");
            HashMap<String, Object> formattedHashMap = new HashMap<>();
            formattedHashMap.put("name", keyValue[0].replaceAll("\"", ""));
            formattedHashMap.put("value", keyValue[1].replaceAll("\"", ""));
            resultList.add(formattedHashMap);
        }

        return resultList;
    }


    public List<HashMap<String, Object>> getDetailImg(int tid) {
        String detailS = productMapper.getDetailImgS(tid);
        detailS = detailS.substring(1, detailS.length() - 1);
        String[] des = detailS.split(",");
        return Arrays.stream(des)
                .map(item -> {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("image", item);
                    return map;
                })
                .collect(Collectors.toList());
    }




//    public List<Product> getProductInfo(int tid){
//        List<Product> productList = new ArrayList<>();
//        List<Integer> pidList1 = null;
//        List<Integer> pidList2 = null;
//
//        YshopMaleList yshopMaleList = productMapper.getMaleInfo(tid);
//        String id1 = yshopMaleList.getVoPid();
//        String id2 = yshopMaleList.getRoPid();
//        if (!id1.equals("[]"))
//             pidList1 = Arrays.stream(id1.substring(1,id1.length() - 1).split(","))
//                    .map(Integer::parseInt)
//                    .toList();
//        if (!id2.equals("[]"))
//            pidList2 = Arrays.stream(id2.substring(1,id2.length() - 1).split(","))
//                .map(Integer::parseInt)
//                .toList();
//
//        if (pidList1 != null){
//            for (int pid:pidList1){
//                Product product = transactionMapper.getProduct(pid);
//                Pattern pattern = Pattern.compile("\\[(.*?)\\]");
//                Matcher matcher = pattern.matcher(product.getIntroduce());
//
//                List<HashMap<String, Object>> resultList = new ArrayList<>();
//
//                while (matcher.find()) {
//                    String pair = matcher.group(1);
//                    String[] keyValue = pair.split(",");
//                    HashMap<String, Object> formattedHashMap = new HashMap<>();
//                    formattedHashMap.put("name", keyValue[0].replaceAll("\"", ""));
//                    formattedHashMap.put("value", keyValue[1].replaceAll("\"", ""));
//                    resultList.add(formattedHashMap);
//                }
//                product.setInfo(resultList);
//                productList.add(product);
//            }
//        }
//        if (pidList2 != null){
//            for (int pid:pidList2){
//                Product product = transactionMapper.getProduct(pid);
//                Pattern pattern = Pattern.compile("\\[(.*?)\\]");
//                Matcher matcher = pattern.matcher(product.getIntroduce());
//
//                List<HashMap<String, Object>> resultList = new ArrayList<>();
//
//                while (matcher.find()) {
//                    String pair = matcher.group(1);
//                    String[] keyValue = pair.split(",");
//                    HashMap<String, Object> formattedHashMap = new HashMap<>();
//                    formattedHashMap.put("name", keyValue[0].replaceAll("\"", ""));
//                    formattedHashMap.put("value", keyValue[1].replaceAll("\"", ""));
//                    resultList.add(formattedHashMap);
//                }
//                product.setInfo(resultList);
//                productList.add(product);
//            }
//        }
//
//        return productList;
//    }
//public List<Product> getProductInfo(int tid) {
//    List<Product> productList = new ArrayList<>();
//    List<Integer> pidList1 = null;
//    List<Integer> pidList2 = null;
//
//    YshopMaleList yshopMaleList = productMapper.getMaleInfo(tid);
//    String id1 = yshopMaleList.getVoPid();
//    String id2 = yshopMaleList.getRoPid();
//
//    if (!id1.equals("[]")) {
//        pidList1 = getPidList(id1);
//        System.out.print("11111111111111111111111111111111111111111+");
//        System.out.print(pidList1);
//    }
//    if (!id2.equals("[]")) {
//        pidList2 = getPidList(id2);
//        System.out.print("222222222222222222222222222222222222222222+");
//        System.out.print(pidList2);
//    }
//
//    processPidList(pidList1, productList);
//    processPidList(pidList2, productList);
//
//    return productList;
//}




    //产品绑定商品
    public boolean  binding (int tid, int pid){
        String tList = productMapper.getTlist(pid);
        List<Integer> pidList = ListStringUtil.idsToList(tList);
        if (pidList.contains(tid)){
            return false;
        }
        else{
            pidList.add(tid);
            String newTlist = ListStringUtil.listToIds(pidList);
            return productMapper.addPid(newTlist);
        }
    }



    private void processPidList(List<Integer> pidList, List<Product> productList) {
        if (pidList!= null) {
            for (int pid : pidList) {
                Product product = transactionMapper.getProduct(pid);
                List<HashMap<String, Object>> resultList = parseIntroduce(product.getIntroduce());
                product.setInfo(resultList);
                productList.add(product);
            }
        }
    }

    private List<HashMap<String, Object>> parseIntroduce(String introduce) {
        Pattern pattern = Pattern.compile("\\[(.*?)\\]");
        Matcher matcher = pattern.matcher(introduce);

        List<HashMap<String, Object>> resultList = new ArrayList<>();

        while (matcher.find()) {
            String pair = matcher.group(1);
            String[] keyValue = pair.split(",");
            HashMap<String, Object> formattedHashMap = new HashMap<>();
            formattedHashMap.put("name", keyValue[0].replaceAll("\"", ""));
            formattedHashMap.put("value", keyValue[1].replaceAll("\"", ""));
            resultList.add(formattedHashMap);
        }
        return resultList;
    }





    public boolean addProduct(Product product){

        return productMapper.insert(product) >0;
    }

    public boolean deleteProductById(Product product){
        return productMapper.deleteProductById(product.getPid());
    }

    public boolean updateProduct(Product product){
        return productMapper.updateProduct(product);
    }

    public  List<Product>  getProducts(Product product){
        if (product.getIsPre() == 0){
            return productMapper.getProductss();
        }
        return productMapper.getProducts(product.getIsPre());
    }

    public List<YshopMaleList> getMaleInfo(){
        return productMapper.getMaleInfo();
    }

    public float getPrice(String pidS){
        float price = 0;
        List<Integer> pidList =  Arrays.stream( pidS.substring(1,  pidS.length() - 1).split(","))
                .map(Integer::parseInt)
                .toList();
        for (int pid:pidList){
            price += productMapper.getPriceByPid(pid);
        }
        return price;
    }

    public String AddMale(List<MultipartFile> files){

        StringBuilder code = new StringBuilder("[");
        for (MultipartFile file : files) {
            code.append(putObject004.uploadFile(file, "male")).append(",");
        }
        if (code.length() > 1) {
            code.deleteCharAt(code.length() - 1);
        }
        code.append("]");
        return code.toString();
    }

    public boolean insertMale(YshopMaleList yshopMaleList){
        yshopMaleList.setCreateTime(new Date());
        yshopMaleList.setUpdateTime(new Date());
        return productMapper.insertMale(yshopMaleList);
    }


    public static String getUniqueCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 12; i++) {
            if (random.nextBoolean()) {
                // 生成数字
                code.append(random.nextInt(10));
            } else {
                code.append((char) (random.nextInt(26) + 'A'));

            }
        }
        return code.toString();
    }

    public boolean insertRedemptionCode(YshopRedemptionCode yshopRedemptionCode){
        yshopRedemptionCode.setCode(getUniqueCode());
        return productMapper.insertRedemptionCode(yshopRedemptionCode);
    }



    public boolean updateMale(MaleList maleList) {
        return  maleListMapper.updateById(maleList)>0;
    }
    public boolean deleteMaleById(YshopMaleList yshopMaleList){
        return productMapper.deleteMaleById(yshopMaleList.getTid());
    }


    public String getUni(String name){
        return productMapper.getUni(name);
    }

    public List<ImgUni> getHomeUni(int type){
        return productMapper.getHomeUni(type);
    }



    public String AddProduct(MultipartFile file) {
        return   putObject004.uploadFile(file, "product");
    }


    public boolean updateAvatar(MultipartFile avatar,String token,Integer pid){
        int uid = jwtService.deconstruction(token).getUid();
        String avatars =  AddProduct(avatar);
        return lambdaUpdate().eq(Product::getPid,pid).set(Product::getImg,avatars).update();
    }

    public  List<String> getProductInfo(int pid, String token){
        int uid = jwtService.deconstruction(token).getUid();
        List<Integer> pidList = productMapper.getUnlockPid(uid);
        if (!pidList.contains(pid))
            return null;
        List<String> result = new ArrayList<>();
        result.add(getTotal(pid));
        result.add(getProgress(pid,uid));
        result.add(getToday(pid,uid,token));
        result.add(getReview(pid,uid,token));
        result.add(getAll(pid,uid));
        return result;
    }

    public String getTotal(int pid){
        return  productMapper.getTotals(pid).toString();
    }

  //今日新学习
    public String getToday(Integer pid,Integer uid,String token) {

        LocalDate time = LocalDate.now();
        List<Integer> newCid = new ArrayList<>();
        Set<Integer> cids = productMapper.getToday(uid, time, pid);

        if (cids == null) {
           return "0";
           }
        for (Integer cid : cids) {
            if(productMapper.getLastDay(uid,pid,cid)==1){
                newCid.add(cid);
            }
        }

        return String.valueOf(newCid.size());
    }




    public  String getAll(int pid,int uid) {
         Set<Integer> getUser= productMapper.getUser(uid,pid);
         Integer Allword=productMapper.getTotals(pid);
         return  (getUser.size()) +" / "+ (Allword);
    }

    //学习进度百分比
    public  String getProgress (int pid,int uid) {
        Set<Integer> getUser= productMapper.getUser(uid,pid);
        Integer Allword = productMapper.getTotals(pid);

        return  String.format("%.2f", ((double) getUser.size()/Allword));
    }


    // 今日需要复习单词
    public String getReview(int pid,int uid ,String token){


        return String.valueOf(recodeService.getReview(pid,token).size());
    }



}

